public class ArrayNesting {

    int count;
    boolean[] flag;
    public int arrayNesting1(int[] nums) {
        int ans = 0;
        flag = new boolean[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < i || flag[i]) continue;
            flag[i] = true;
            count = 1;
            dfs(nums[i], i, nums);
            ans = Math.max(ans, count);
        }
        return ans;
    }

    public void dfs(int i, int target, int[] nums) {
        flag[i] = true;
        if (i == target) return;
        ++count;
        i = nums[i];
        dfs(i, target, nums);
    }

    public int arrayNesting(int[] nums) {
        int ans = 0;
        int count;
        for (int i = 0; i < nums.length; i++) {
            count = 0;
            int index = i;
            while (nums[index] != -1) {
                int temp = nums[index];
                nums[index] = -1;
                index = temp;
                ++count;
            }
            ans = Math.max(ans, count);
        }
        return ans;
    }
}
